﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Globalization;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;

namespace DalatCooking.Core.Web.Controls
{
    public class DalatGreenPage : BasePage
    {
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
       //     this.MasterPageFile = @"/themes/" + Settings.Setting("site.theme") + "/MasterPage.master";
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);            
        }
        private static readonly Regex BodyRegex = new Regex(@"\[UserControl:(.*?)\]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        public static void InjectUserControls(System.Web.UI.Control containerControl, string content)
        {
            var currentPosition = 0;
            var matches = BodyRegex.Matches(content);
            var containerControls = containerControl.Controls;
            var page = containerControl.Page;

            foreach (Match match in matches)
            {
                // Add literal for content before custom tag should it exist.
                if (match.Index > currentPosition)
                {
                    containerControls.Add(new LiteralControl(content.Substring(currentPosition, match.Index - currentPosition)));
                }

                // Now lets add our user control.
                try
                {
                    var all = match.Groups[1].Value.Trim();
                    Control usercontrol;

                    if (!all.EndsWith(".ascx", StringComparison.OrdinalIgnoreCase))
                    {
                        var index = all.IndexOf(".ascx", StringComparison.OrdinalIgnoreCase) + 5;
                        usercontrol = page.LoadControl(all.Substring(0, index));

                        var parameters = page.Server.HtmlDecode(all.Substring(index));
                        var type = usercontrol.GetType();
                        var paramCollection = parameters.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

                        foreach (var param in paramCollection)
                        {
                            var paramSplit = param.Split('=');
                            var name = paramSplit[0].Trim();
                            var value = paramSplit[1].Trim();
                            var property = type.GetProperty(name);
                            property.SetValue(
                                usercontrol,
                                Convert.ChangeType(value, property.PropertyType, CultureInfo.InvariantCulture),
                                null);
                        }
                    }
                    else
                    {
                        usercontrol = page.LoadControl(all);
                    }

                    containerControls.Add(usercontrol);

                    // Now we will update our position.
                    // currentPosition = myMatch.Index + myMatch.Groups[0].Length;
                }
                catch (Exception)
                {
                    // Whoopss, can't load that control so lets output something that tells the developer that theres a problem.
                    containerControls.Add(
                        new LiteralControl(string.Format("ERROR - UNABLE TO LOAD CONTROL : {0}", match.Groups[1].Value)));
                }

                currentPosition = match.Index + match.Groups[0].Length;
            }

            // Finally we add any trailing static text.
            containerControls.Add(
                new LiteralControl(content.Substring(currentPosition, content.Length - currentPosition)));
        }

        protected override void OnPreLoad(EventArgs e)
        {
            /*
            string appKey=AppConfig.Instance().GetValueString("ApplicationKey");
            if (!IsPostBack)
            {
                if (AppConfig.Instance().GetValueInt("Install") == 1)
                    Response.Redirect("/install");
            }
            
            if (!appKey.Equals( MyEncode.Encrypt("LeThanhTuan").ToUpper()))
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alert",
              "alert('Cảnh báo: Website chưa có bản quyền. Vui lòng liên hệ 097 6060 432 (A. Tuấn) để mua bản quyền cho website của bạn.!');", true);
            }
            */
            base.OnPreLoad(e);
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
          
          //  AddGlobalStyles(@"/themes/" + Settings.Setting("site.theme") + "/css");
         //   AddGlobalJs( @"/themes/" + Settings.Setting("site.theme") + "/js");           
        }
        
        protected override void InitializeCulture()
        {
            //if (Session["CultureInfo"] == null)
            //    Session["CultureInfo"] = "vi-VN";
            //if (Session["CultureInfo"] != null)
            //{
            //    Thread.CurrentThread.CurrentCulture =
            //        CultureInfo.CreateSpecificCulture(Session["CultureInfo"].ToString());
            //    Thread.CurrentThread.CurrentUICulture = new
            //        CultureInfo(Session["CultureInfo"].ToString());
            //}
            base.InitializeCulture();
        }

        public string LanguageID
        {
            get
            {
                if (Session["CultureInfo"] == null || Session["CultureInfo"].ToString() == "vi-VN") return "vi-VN";
                else return "en-US";
            }
        }
        
    }
}
